<template>
  <div class="config-view">
    <!-- 平台选择 -->
    <div class="config-section">
      <div class="section-title">🎯 平台选择</div>
      <div class="platform-grid">
        <div
          v-for="platform in platforms"
          :key="platform.value"
          class="platform-card"
          :class="{ selected: config.platform === platform.value }"
          @click="selectPlatform(platform.value)"
        >
          <span class="platform-icon">{{ platform.icon }}</span>
          <span class="platform-name">{{ platform.label }}</span>
        </div>
      </div>
    </div>

    <!-- 基础配置 -->
    <div class="config-section">
      <div class="section-title">🔧 基础配置</div>
      <el-form :model="config" label-width="80px" size="small">
        <el-row :gutter="12">
          <el-col :span="8">
            <el-form-item label="爬取类型">
              <el-select v-model="config.crawlerType" style="width: 100%">
                <el-option label="关键词搜索" value="search" />
                <el-option label="指定帖子" value="detail" />
                <el-option label="创作者主页" value="creator" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="登录方式">
              <el-select v-model="config.loginType" style="width: 100%">
                <el-option label="二维码登录" value="qrcode" />
                <el-option label="手机号登录" value="phone" />
                <el-option label="Cookie登录" value="cookie" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="数据保存">
              <el-select v-model="config.saveDataOption" style="width: 100%">
                <el-option label="SQLite数据库" value="sqlite" />
                <el-option label="MySQL数据库" value="mysql" />
                <el-option label="JSON文件" value="json" />
                <el-option label="CSV文件" value="csv" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        
        <el-form-item label="关键词">
          <el-input
            v-model="config.keywords"
            type="textarea"
            :rows="2"
            placeholder="请输入搜索关键词，多个关键词用逗号分隔"
          />
        </el-form-item>
        
        <el-row :gutter="12">
          <el-col :span="8">
            <el-form-item label="爬取数量">
              <el-input-number
                v-model="config.crawlCount"
                :min="1"
                :max="10000"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="起始页码">
              <el-input-number
                v-model="config.startPage"
                :min="1"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="并发数">
              <el-input-number
                v-model="config.concurrency"
                :min="1"
                :max="10"
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <!-- 高级选项 -->
    <div class="config-section">
      <div class="section-title">📋 高级选项</div>
      <div class="options-grid">
        <el-checkbox v-model="config.enableComments">爬取一级评论</el-checkbox>
        <el-checkbox v-model="config.enableSubComments">爬取二级评论</el-checkbox>
        <el-checkbox v-model="config.enableMedia">下载媒体文件</el-checkbox>
        <el-checkbox v-model="config.enableProxy">启用IP代理</el-checkbox>
      </div>
    </div>

    <!-- 任务控制 -->
    <div class="config-section">
      <div class="section-title">🎮 任务控制</div>
      <div class="task-controls">
        <el-button type="success" @click="startCrawling" :disabled="isRunning">
          📤 提交任务
        </el-button>
        <el-button @click="saveConfig">
          💾 保存配置
        </el-button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router'
import { useAppStore } from '@/stores/app'
import { submitTask } from '@/api/crawler'

const router = useRouter()
const appStore = useAppStore()
const config = computed(() => appStore.config)

const platforms = [
  { value: 'xhs', label: '小红书', icon: '🔴' },
  { value: 'douyin', label: '抖音', icon: '🎵' },
  { value: 'kuaishou', label: '快手', icon: '⚡' },
  { value: 'bilibili', label: 'B站', icon: '📺' },
  { value: 'weibo', label: '微博', icon: '📱' },
  { value: 'zhihu', label: '知乎', icon: '🗣️' },
]

// 任务状态
const isRunning = ref(false)

const selectPlatform = (platform: string) => {
  appStore.updateConfig({ platform })
}

// 任务控制函数
const startCrawling = async () => {
  console.log('🚀 提交任务按钮被点击')
  
  // 验证配置
  if (!config.value.keywords.trim()) {
    console.log('❌ 验证失败: 关键词为空')
    ElMessage.error('请输入搜索关键词')
    return
  }
  
  if (config.value.platform !== 'zhihu') {
    console.log('❌ 验证失败: 平台不是知乎，当前平台:', config.value.platform)
    ElMessage.warning('目前仅支持知乎平台，请选择知乎')
    return
  }

  console.log('✅ 配置验证通过')
  console.log('📋 当前配置:', {
    platform: config.value.platform,
    keywords: config.value.keywords,
    crawlCount: config.value.crawlCount,
    crawlerType: config.value.crawlerType
  })

  try {
    console.log('🔄 设置提交状态为 true')
    isRunning.value = true
    
    console.log('📡 准备提交任务')
    
    const taskConfig = {
      platform: config.value.platform,
      crawler_type: config.value.crawlerType,
      login_type: "qrcode", // 固定使用二维码登录
      save_data_option: "sqlite", // 固定使用SQLite
      keywords: config.value.keywords,
      crawl_count: config.value.crawlCount,
      start_page: config.value.startPage,
      concurrency: config.value.concurrency,
      enable_comments: config.value.enableComments,
      enable_sub_comments: config.value.enableSubComments,
      enable_media: config.value.enableMedia,
      enable_proxy: config.value.enableProxy,
      task_name: `${getPlatformName(config.value.platform)}-${config.value.keywords.split(',')[0]}搜索`
    }
    
    console.log('📤 发送任务配置到后端:', taskConfig)
    
    try {
      // 提交任务到Rust后端，由Rust启动子线程执行Python脚本
      const result = await submitTask(taskConfig)
      console.log('✅ 后端响应:', result)
      
      ElMessage.success('任务提交成功，请在监控页面查看进度')
      
      // 重置状态
      isRunning.value = false
      
      // 跳转到监控页面
      router.push('/monitor')
    } catch (submitError) {
      console.error('❌ 提交任务失败 (内部错误):', submitError)
      
      // 尝试使用startCrawler作为备选方法
      console.log('🔄 尝试使用startCrawler作为备选方法')
      const { invoke } = await import('@tauri-apps/api/core')
      const result = await invoke('start_crawler', { config: taskConfig })
      console.log('✅ 备选方法响应:', result)
      
      ElMessage.success('任务提交成功（备选方法），请在监控页面查看进度')
      
      // 重置状态
      isRunning.value = false
      
      // 跳转到监控页面
      router.push('/monitor')
    }
  } catch (error) {
    console.error('❌ 提交任务失败:', error)
    console.error('错误详情:', {
      name: error.name,
      message: error.message,
      stack: error.stack
    })
    ElMessage.error(`提交失败: ${error}`)
    isRunning.value = false
  }
}

// 获取平台名称
const getPlatformName = (platform: string) => {
  const platformMap: Record<string, string> = {
    xhs: '小红书',
    douyin: '抖音',
    kuaishou: '快手',
    bilibili: 'B站',
    weibo: '微博',
    zhihu: '知乎',
  }
  return platformMap[platform] || platform
}

const saveConfig = async () => {
  try {
    const { invoke } = await import('@tauri-apps/api/core')
    await invoke('save_config', { config: config.value })
    ElMessage.success('配置已保存')
  } catch (error) {
    console.error('保存配置失败:', error)
    ElMessage.error(`保存失败: ${error}`)
  }
}
</script>

<style scoped>
.config-view {
  height: 100%;
  overflow-y: auto;
  padding: 0 16px;
}

.config-section {
  background: white;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 12px;
  border: 1px solid #e0e6ed;
}

.section-title {
  font-size: 16px;
  font-weight: 600;
  color: #495057;
  margin-bottom: 12px;
  display: flex;
  align-items: center;
  gap: 6px;
}

/* 平台选择 */
.platform-grid {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 8px;
}

.platform-card {
  padding: 12px 8px;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  text-align: center;
  cursor: pointer;
  transition: all 0.2s;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.platform-card:hover {
  border-color: var(--el-color-primary);
  box-shadow: 0 2px 8px rgba(102, 126, 234, 0.15);
}

.platform-card.selected {
  border-color: var(--el-color-primary);
  background: var(--el-color-primary-light-9);
}

.platform-icon {
  font-size: 20px;
}

.platform-name {
  font-size: 14px;
  font-weight: 500;
  color: #495057;
}

/* 高级选项 */
.options-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 12px;
}

/* 任务控制 */
.task-controls {
  display: flex;
  gap: 12px;
  justify-content: center;
}

.task-controls .el-button {
  font-size: 14px;
  padding: 10px 20px;
}

/* 表单样式优化 */
:deep(.el-form-item) {
  margin-bottom: 12px;
}

:deep(.el-form-item__label) {
  font-size: 14px;
  line-height: 1.2;
}

:deep(.el-input__inner),
:deep(.el-select .el-input__inner),
:deep(.el-input-number .el-input__inner) {
  font-size: 14px;
}

:deep(.el-textarea__inner) {
  font-size: 14px;
}

:deep(.el-checkbox) {
  font-size: 14px;
  margin-right: 0;
}

:deep(.el-checkbox__label) {
  font-size: 14px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .platform-grid {
    grid-template-columns: repeat(3, 1fr);
  }
  
  .options-grid {
    grid-template-columns: repeat(2, 1fr);
  }
  
  .task-controls {
    flex-direction: column;
  }
}
</style>